<template>
  <div class="product-list-container">
    <div class="navbar">
      <div @click="goBack" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="navbar-title">宠物商品</div>
      <div>
        <i class="fas fa-th-large"></i>
      </div>
    </div>
    
    <div class="header">
      <div class="search-bar">
        <i class="fas fa-search search-icon"></i>
        <input type="text" class="search-input" v-model="searchQuery" placeholder="搜索宠物或商品" @input="searchProducts">
      </div>
    </div>
    
    <div class="category-nav">
      <div 
        v-for="(category, index) in categories" 
        :key="index" 
        :class="['category-item', (selectedCategory === 0 && category.categoryId === 0) || 
                              (selectedCategory !== 0 && String(category.categoryId) === String(selectedCategory)) ? 'active' : '']"
        @click="selectCategory(category.categoryId)"
      >
        {{ category.name }}
      </div>
    </div>
    
    <div class="filter-bar">
      <div 
        :class="['filter-item', sortBy === 'comprehensive' ? 'active' : '']"
        @click="setSortBy('comprehensive')"
      >
        综合排序
        <i class="fas fa-angle-down filter-icon"></i>
      </div>
      <div 
        :class="['filter-item', sortBy === 'sales' ? 'active' : '']"
        @click="setSortBy('sales')"
      >
        销量优先
      </div>
      <div 
        :class="['filter-item', sortBy.startsWith('price') ? 'active' : '']"
        @click="togglePriceSort"
      >
        价格
        <i v-if="sortBy === 'price_asc'" class="fas fa-sort-up"></i>
        <i v-else-if="sortBy === 'price_desc'" class="fas fa-sort-down"></i>
        <i v-else class="fas fa-sort"></i>
      </div>
      <div class="filter-item" @click="showFilterOptions = !showFilterOptions">
        筛选
        <i class="fas fa-filter filter-icon"></i>
      </div>
    </div>
    
    <div class="container">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="filteredProducts.length === 0" class="empty-state">
        <i class="fas fa-search fa-3x"></i>
        <p>未找到相关商品</p>
      </div>
      
      <div v-else class="product-grid">
        <router-link 
          v-for="product in filteredProducts" 
          :key="product.productId"
          :to="{ path: `/product/${product.productId}` }" 
          class="product-card"
        >
          <div style="position: relative;">
            <img class="product-image" :src="product.mainImage" :alt="product.name">
            <span v-if="product.categoryName" class="category-badge">{{ product.categoryName }}</span>
          </div>
          <div class="product-info">
            <div class="product-name">{{ product.name }}</div>
            <div class="product-price">¥{{ product.price }}</div>
            <div class="product-meta">
              <div class="product-store">{{ product.storeName }}</div>
              <div class="product-sales">
                <span v-if="product.stock !== undefined && product.saleCount !== undefined && product.stock === product.saleCount" class="sold-out">售罄</span>
                <span v-else class="stock-info">销量 {{ product.salesCount || 0 }}</span>
              </div>
            </div>
          </div>
        </router-link>
      </div>
    </div>
    
    <TabBar />
  </div>
</template>

<script>
import TabBar from '@/components/TabBar.vue'
import api from '@/network/api'

export default {
  name: 'ProductListView',
  components: {
    TabBar
  },
  data() {
    return {
      loading: true,
      products: [],
      categories: [
        { categoryId: 0, name: '全部' }
      ],
      selectedCategory: 0,
      sortBy: 'comprehensive',
      searchQuery: '',
      showFilterOptions: false,
      priceRange: [0, Infinity],
      searchTimeout: null // 添加搜索延时计时器
    }
  },
  computed: {
    filteredProducts() {
      let result = [...this.products]
      
      // 搜索由API处理，只保留价格过滤
      result = result.filter(product => 
        product.price >= this.priceRange[0] && product.price <= this.priceRange[1]
      )
      
      return result
    }
  },
  methods: {
    async fetchCategories() {
      try {
        await api.getCategories()
        .then(res => {
          if (res.data.data && res.data.data.length > 0) {
            // 添加"全部"分类
            const allCategory = { categoryId: 0, name: '全部' };
            this.categories = [allCategory, ...res.data.data];
          }
        })
        .catch(err => {
          console.error('获取分类失败:', err);
        })
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    },

    goBack() {
      this.$router.go(-1);
    },
    
    async fetchProducts() {
      try {
        this.loading = true;
        
        let apiCall;
        const storeId = this.$route.params.storeId;
        
        // 根据排序方式选择不同的API调用
        if (this.sortBy === 'sales') {
          apiCall = api.getOrderBySales(this.selectedCategory);
        } else if (this.sortBy === 'price_asc') {
          apiCall = api.getOrderByPrice(this.selectedCategory);
        } else if (this.sortBy === 'price_desc') {
          apiCall = api.getReOrderByPrice(this.selectedCategory);
        } else if (this.selectedCategory !== 0) {
          // 使用按分类获取商品的接口
          apiCall = api.getProductsByCategory(this.selectedCategory);
        } else {
          // 获取全部商品
          apiCall = api.getProductsList(storeId);
        }
        
        await apiCall
          .then(res => {
            if (res.data && res.data.data && res.data.data.length > 0) {
              this.products = res.data.data;
            } else {
              this.products = [];
            }
          })
          .catch(err => {
            console.error('获取商品列表失败:', err);
            this.products = [];
          });
        
        this.loading = false;
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.loading = false;
        this.products = [];
      }
    },
    
    selectCategory(categoryId) {
      this.selectedCategory = categoryId;
      // 检查是否有搜索关键词，如果有则执行搜索，否则获取普通商品列表
      if (this.searchQuery.trim()) {
        this.searchProducts();
      } else {
      this.fetchProducts();
      }
    },
    
    setSortBy(sortType) {
      this.sortBy = sortType;
      this.fetchProducts();
    },
    
    togglePriceSort() {
      if (this.sortBy === 'price_asc') {
        this.sortBy = 'price_desc';
      } else if (this.sortBy === 'price_desc' || this.sortBy !== 'price_asc') {
        this.sortBy = 'price_asc';
      }
      this.fetchProducts();
    },
    
    searchProducts() {
      // 清除之前的定时器
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout);
      }
      
      // 设置新的定时器，延迟300ms后执行搜索
      this.searchTimeout = setTimeout(() => {
        // 如果搜索关键词为空，恢复到默认列表显示
        if (!this.searchQuery.trim()) {
          this.fetchProducts();
          return;
        }
        
        // 显示加载状态
        this.loading = true;
        
        // 调用搜索API
        api.searchProducts(this.searchQuery.trim())
          .then(res => {
            if (res.data && res.data.code === 100) {
              // 更新商品数据
              let searchResults = res.data.data || [];
              
              // 如果选择了特定分类，过滤搜索结果
              if (this.selectedCategory !== 0) {
                searchResults = searchResults.filter(product => 
                  String(product.categoryId) === String(this.selectedCategory)
                );
              }
              
              this.products = searchResults;
            } else {
              console.error('搜索失败:', res.data.message);
              this.products = [];
            }
          })
          .catch(err => {
            console.error('搜索出错:', err);
            this.products = [];
          })
          .finally(() => {
            this.loading = false;
          });
      }, 300);
    }
  },
  created() {
    // 首先从URL查询参数获取类别ID
    const categoryFromQuery = this.$route.query.category;
    if (categoryFromQuery) {
      this.selectedCategory = Number(categoryFromQuery);
    } else {
      // 从localStorage读取选中的分类
      const savedCategory = localStorage.getItem('selectedCategory');
      if (savedCategory !== null) {
        this.selectedCategory = Number(savedCategory);
        // 使用后清除，避免影响后续访问
        localStorage.removeItem('selectedCategory');
      }
    }
    
    this.fetchCategories();
    this.fetchProducts();
  }
}
</script>

<style scoped>
.product-list-container {
  width: 100%;
  padding-bottom: 70px; /* 为底部导航栏留出空间 */
  background-color: #f8f9fa; /* 添加浅灰色背景 */
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #e2e8f0; /* 使用细线代替阴影 */
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-back {
  color: #2d3748;
  text-decoration: none;
  font-size: 18px;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600; /* 加粗标题 */
}

.header {
  padding: 10px 15px; /* 调整内边距 */
  background-color: white;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #f1f5f9;
  border-radius: 8px; /* 更现代的圆角 */
  padding: 10px 15px; /* 调整内边距 */
}

.search-icon {
  color: #94a3b8;
  margin-right: 10px; /* 增加图标与文字间距 */
}

.search-input {
  border: none;
  background-color: transparent;
  outline: none;
  flex: 1;
  font-size: 14px;
}

.search-input::placeholder {
  color: #94a3b8;
}

.category-nav {
  overflow-x: auto;
  white-space: nowrap;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 10px 15px; /* 增加左右内边距 */
  scrollbar-width: none; /* For Firefox */
  -ms-overflow-style: none;  /* For Internet Explorer and Edge */
}

.category-nav::-webkit-scrollbar {
  display: none; /* For Chrome, Safari, and Opera */
}

.category-item {
  display: inline-block;
  padding: 8px 15px; /* 调整内边距，使其更大更易点击 */
  margin-right: 10px; /* 增加项之间的间距 */
  color: #4a5568;
  font-size: 14px;
  cursor: pointer;
  border-radius: 18px; /* 胶囊形状 */
  transition: all 0.3s ease;
}

.category-item.active {
  color: white; /* 激活时文字变白 */
  font-weight: 500;
  background-color: #3490dc; /* 激活时背景变蓝 */
}

.category-item.active:after {
 content: none; /* 移除旧的下划线样式 */
}

.filter-bar {
  display: flex;
  padding: 15px; /* 增加内边距 */
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  font-size: 14px; /* 稍大字体 */
  position: sticky; /* 粘性定位 */
  top: 53px; /* 修正：精确计算 navbar 高度 */
  z-index: 99;
  justify-content: space-around; /* 均匀分布 */
}

.filter-item {
  display: flex;
  align-items: center;
  margin-right: 0; /* 移除右边距，由 justify-content 控制 */
  color: #4a5568;
  cursor: pointer;
  transition: color 0.3s ease;
}

.filter-item.active {
  color: #3490dc;
  font-weight: 600; /* 加粗 */
}

.filter-icon {
  margin-left: 5px; /* 调整图标间距 */
}

.container {
  padding: 0; /* 移除旧的 padding，由 grid 控制 */
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px; /* 调整间隙 */
  padding: 10px; /* 容器内边距 */
}

.product-card {
  background-color: white;
  border-radius: 12px; /* 更大的圆角 */
  overflow: hidden;
  border: none; /* 移除边框 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); /* 使用更柔和的阴影 */
  cursor: pointer;
  text-decoration: none;
  color: inherit;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product-card:hover {
  transform: translateY(-5px); /* 添加轻微的悬浮效果 */
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.product-image {
  width: 100%;
  height: 160px; /* 增加图片高度 */
  object-fit: cover;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-weight: 500;
  font-size: 14px;
  color: #2d3748;
  margin-bottom: 8px; /* 调整间距 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-price {
  color: #e53e3e;
  font-weight: bold;
  font-size: 18px; /* 价格更突出 */
  margin-bottom: 8px;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #a0aec0;
}

.product-store {
  color: #718096;
}

.product-sales {
  color: #a0aec0;
}

.sold-out {
  color: #e53e3e;
  font-weight: 500;
  background-color: #fee2e2;
  padding: 2px 6px;
  border-radius: 4px;
}

.stock-info {
  color: #38a169;
  font-weight: 500;
  background-color: #e6fffa;
  padding: 2px 6px;
  border-radius: 4px;
}

.category-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 10px;
  backdrop-filter: blur(2px); /* 添加毛玻璃效果 */
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3490dc;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #a0aec0;
}

.empty-state i {
  margin-bottom: 15px;
}

@media (max-width: 640px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 10px;
  }
  
  .product-card {
    border-radius: 8px;
  }
  
  .product-image {
    height: 120px;
  }
}

@media (min-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (min-width: 1024px) {
  .product-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style> 